<%--
  Created by IntelliJ IDEA.
  User: xdzy
  Date: 2017/4/5
  Time: 23:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html class="no-js fixed-layout">
<head>
    <base href="<%=basePath%>">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>首页</title>
    <meta name="description" content="这是一个 index 页面">
    <meta name="keywords" content="index">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-title" content="Amaze UI" />
    <link rel="stylesheet" href="./resources/css/amazeui.min.css"/>
    <link rel="stylesheet" href="./resources/css/admin.css">
    <link rel="stylesheet" href="./resources/css/style.css">
</head>
<body>
<jsp:include page="common1.jsp"/>
<div class="am-cf admin-main">
    <!-- sidebar start -->
    <div class="admin-sidebar am-offcanvas" id="admin-offcanvas">
        <div class="am-offcanvas-bar admin-offcanvas-bar">
            <ul class="am-list admin-sidebar-list">
                <c:forEach items="${requestScope.groupList}" var="item" varStatus="i">
                    <li class="admin-parent">
                        <a class="am-cf" data-am-collapse="{target: '#group${i.index}'}">
                            <span class="am-icon-users"></span><span>${item.groupName}</span>
                           <%-- <span class="am-badge am-badge-danger am-round" >&nbsp;</span>--%>
                            <span class="am-icon-angle-right am-fr am-margin-right"></span>
                        </a>
                        <ul class="am-list am-collapse admin-sidebar-sub" id="group${i.index}">
                            <c:forEach items="${item.friends}" var="friend">
                               <li>
                                <img onclick="openFriendInfo('${friend.fid}','${friend.fu.username}','${friend.fu.nickName}','${friend.fu.headImg}','${friend.fu.email}','${friend.alias}')"
                                        style="margin-left:3px;border-radius:15px;vertical-align:middle;display: inline-block" width='38' height='38' src="./resources/images/${friend.fu.headImg}">
                                <a style="width:75%;display: inline-block" href="javascript:createNewChat('${friend.fu.uid}','${friend.alias}','${friend.fu.headImg}')">
                                        ${friend.alias}<span class="am-badge am-badge-danger am-round" id="unread_${friend.fu.uid}"></span>
                                </a>
                                </li>
                            </c:forEach>
                        </ul>
                    </li>
                </c:forEach>
            </ul>

        </div>
    </div>
    <!-- sidebar end -->
    <!-- content start -->
    <div class="admin-content">
        <div class="admin-content-body">
                <div id="tt"  class="easyui-tabs" style="width:720px;height:600px;display: none;">

                </div>
        </div>
    </div>
</div>
<a href="#" class="am-icon-btn am-icon-th-list am-show-sm-only admin-menu" data-am-offcanvas="{target: '#admin-offcanvas'}"></a>
<jsp:include page="common2.jsp"/>
<!-- 好友信息-->
<div id="dd">
    <img src="" alt="头像走丢啦！" id="friend_info_headImg" width="100px" height="100px"><br>
    <span style="color: red" id="friend_info_tips"></span><br>
    <input type="hidden" id="friend_info_id" value=""><br>
    备注：<input type="text" value="" id="friend_info_alias"><br>
    好友账号：<span id="friend_info_username"></span><br>
    昵称：<span id="friend_info_nickName"></span><br>
    好友邮箱：<span id="friend_info_email"></span><br>
    <button id="updateAlias" class="am-btn am-btn-success">修改备注</button>
    <button id="deleteFriend" class="am-btn am-btn-danger">删除好友</button>
    <button id="closeInfoModal" class="am-btn am-btn-default">关闭</button>
</div>
<link rel="stylesheet" type="text/css" href="./resources/css/easyui.css">
<link rel="stylesheet" type="text/css" href="./resources/css/icon.css">
<script type="text/javascript" src="./resources/js/jquery.easyui.min.js"></script>

<script>
    var fuid
    var tabCount=0;
    $(function () {
        var unreads=${requestScope.unreads};
        if(unreads!=""){
            var u=unreads;
            for(i=0;i<u.length;i++){
                func(u[i])
            }
            $("#top_advice").text("新消息")
        }
    })
    function openFriendInfo(id,username,nickName,headImg,email,alias) {

        $("#friend_info_id").val(id)
        $("#friend_info_alias").val(alias);
        $("#friend_info_username").text(username);
        $("#friend_info_nickName").text(nickName)
        $("#friend_info_headImg").attr("src","./resources/images/"+headImg)
        $("#friend_info_email").text(email);
        $('#dd').dialog({
            title: '好友信息',
            width: 330,
            height: 300,
            closed: false,
            cache: false,
            modal: true,
        });
    }
    $("#updateAlias").click(function () {
        $.post("./friedop_updateAlias.action",{
            "alias":$("#friend_info_alias").val(),
            "id": $("#friend_info_id").val()
        },function (data) {
            if(data=="success"){
                $("#friend_info_tips").text("更新成功");
            }else{
                $("#friend_info_tips").text("更新失败，请重试");
            }
        })
    })
    $("#deleteFriend").click(function () {
        if(confirm("确认删除当前好友吗？")){
            $.post("./friedop_deleteFriend.action",{
                "id": $("#friend_info_id").val()
            },function (data) {
                window.location.href="./home.action"
            })
        }else{

        }
    })
    $("#closeInfoModal").click(function () {
        $("#dd").dialog('close');
    })

    window.onbeforeunload=function (event) {
        websocket.close();
    }
    //打开一个新的聊天窗口
    function createNewChat(id,alias,headImg) {

        addTab(alias,id);
    }
    function showUnReadMessage(msgs) {
        for(i=0;i<msgs.length;i++){
            //$("#msgs").html($("#msgs").html() + "<br/>" +falias+"的消息:"+msgs[i].content);
            //showMsg_friend(msgs[i].content,msgs[i].from)
            var temp="<span style='color:green'>好友的消息("+msgs[i].date+")：</span>"+msgs[i].content;
            showMsg(temp,msgs[i].from)
        }
    }
    var websocket;
    $(function () {
        if ('WebSocket' in window) {
            var url = 'ws://' + window.location.host + '/Chat/webChat/${sessionScope.loginUser.uid}';
            websocket = new WebSocket(url);
        }
        websocket.onopen = function(evnt) {
        };
        websocket.onmessage = function(evnt) {
            var msg=JSON.parse(evnt.data)
            if(msg.type=="advice"){
               func(msg.from)
                $("#top_advice").text("新消息")
            }else{
                //$("#msgs").html($("#msgs").html() + "<br/>" +falias+"的消息:"+evnt.data);
                //showMsg_friend(msg.content,msg.from)
                var temp="<span style='color:green'>好友的消息("+msg.date+")：</span>"+msg.content;
                showMsg(temp,msg.from)
            }
        };
        websocket.onerror = function(evnt) {
        };
        websocket.onclose = function(evnt) {
        }
    })
    function send(id) {
        var text=$("#content"+id).text();
        var time = getNowFormatDate();
        var msg={"from":"${sessionScope.loginUser.uid}",
            "to":fuid,"content":text,"type":"text","date":time}
        var temp="<span style='color:red'>我的消息("+msg.date+")：</span>"+text;
        showMsg(temp,id)
        websocket.send(JSON.stringify(msg));
        $("#content"+id).text("");
    }
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
        return currentdate;
    }
    function func(id) {
        $("#unread_"+id).html("&nbsp;")
    }
    function addTab(title,id){
        if ($('#tt').tabs('exists', title)){
            $('#tt').tabs('select', title);
        } else {
            var content = makeChatBox(title,id);
            $('#tt').tabs('add',{
                title:title,
                content:content,
                closable:true,
            });
            tabCount++;
            if(tabCount==1){
                $("#tt").css("display","")
            }
        }
    }
    $('#tt').tabs({
        onClose: function(title,index){
            alert("确认关闭吗")
            tabCount--;
            if(tabCount<1){
                $("#tt").css("display","none")
            }
        }
    });
    $('#tt').tabs({
        border:false,
        onSelect:function(title,index){
            $("#unread_"+$("#chatbox_"+title).val()).html("")
            $("#top_advice").text("")
            $.post("./beginChat.action",{"fuid":$("#chatbox_"+title).val()},function (data) {
                fuid=$("#chatbox_"+title).val()
                if(data!="[]"&&data!=""){
                    showUnReadMessage(JSON.parse(data))
                }
            })
        }
    });
    function makeChatBox(title,id){
        var c='<input type="hidden" value="'+id+'" id="chatbox_'+title+'">'+
            '<div id="show'+id+'" style="border: solid;width: 700px;height: 400px;overflow-y:auto"></div>'+
            '<div id="content'+id+'" style="border: solid;width: 700px;height: 100px;overflow-y:auto" contenteditable="true">'+
            '</div>'+
            '<div id="btns" style="border: solid;width: 700px;height: 30px;">'+
            '<div align="right"><button onclick="send('+id+')">发送</button></div>'+
            '</div>';
        return c;
    }
    function showMsg(temp,id){
        $("#show"+id).html($("#show"+id).html()+""+temp+"<BR>")
        $('#show'+id).scrollTop( $('#show'+id)[0].scrollHeight );
    }
</script>
</body>
</html>
